package com.hxzy.shop.utils;

import com.hxzy.shop.enums.BucketNameType;
import com.hxzy.shop.vo.ApiException;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;

import static com.hxzy.shop.enums.BucketNameType.OTHER_BUCKETNAME;

/**
 * @Author ht
 * @Date 2021/8/3 9:05
 * @Version 1.0
 */
public class TencentCosUtils {


    public static final String SECRETID="AKIDXxCdEj5E9qKcfT3OVP6appa8QnywhCST";
    public static final String SECRETKEY="2qQnyvc4HFyTmsjKhogJm10lHXXJrDMG";
    public static final String APPID="-1303155159";


//    public static final String SECRETID="AKIDay6yZtwiDSQ7XgZBWaOvBAsJSKvGK7ew";
//    public static final String SECRETKEY="2nHVS7WeV5NO9dqlRqsd8MJzOWNwFH2W";
//    public static final String APPID="-1306997872";
    private static COSClient getCOSClient() {
        //1 初始化用户身份信息
        COSCredentials cred = new BasicCOSCredentials(SECRETID, SECRETKEY);
        // 2 设置 bucket 的地域,clientConfig 中包含了设置 region, https
        ClientConfig clientConfig = new ClientConfig(new Region("ap-chongqing"));
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


    public static String uploadfile(MultipartFile file, Boolean bucketType) {
        if (ObjectUtils.isEmpty(file)) {
            throw new ApiException(500, "文件不能为空");
        }
        //图片大小限制 不能超过2M
        if (file.getSize() > 1024 * 1024 * 2) {
            throw new ApiException(500, "图片大小不能超过2M");
        }
        String bucketName = null;
        if (bucketType) {
            bucketName = BucketNameType.DRUG_BUCKETNAME + APPID;
        } else {
            bucketName = BucketNameType.OTHER_BUCKETNAME + APPID;
        }
        COSClient cosClient = null;
        String fileName = null;
        try {
            cosClient = getCOSClient();
            //上传图片
            fileName = file.getOriginalFilename();
            String substring = fileName.substring(fileName.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), substring);
            file.transferTo(localFile);
            Random random = new Random();
            //图片名称
            fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName, fileName, localFile);
            cosClient.putObject(objectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        //图片路径url
        return cosClient.getObjectUrl(bucketName, fileName).toString();
    }

    public static String  UploadQrCodeFile(File file,Boolean bucketType){
        if (ObjectUtils.isEmpty(file)) {
            throw new ApiException(500, "文件不能为空");
        }
        String bucketName = null;
        if (bucketType) {
            bucketName = BucketNameType.DRUG_BUCKETNAME + APPID;
        } else {
            bucketName = BucketNameType.OTHER_BUCKETNAME + APPID;
        }
        COSClient cosClient = null;
        String fileName = null;
        try {
            cosClient = getCOSClient();
            //上传图片
            fileName =file.getName();
            String substring = fileName.substring(fileName.lastIndexOf("."));
            Random random = new Random();
            //图片名称
            fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName, fileName, file);
            cosClient.putObject(objectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        //图片路径url
        return cosClient.getObjectUrl(bucketName, fileName).toString();
    }
    public static Boolean deleteFile(Boolean bucketType, String fileName) {
        COSClient cosClient = null;
        try {
            String bucketName = null;
            if (bucketType) {
                bucketName = BucketNameType.DRUG_BUCKETNAME + APPID;
            } else {
                bucketName = BucketNameType.OTHER_BUCKETNAME + APPID;
            }
            cosClient = getCOSClient();
            cosClient.deleteObject(bucketName, fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            cosClient.shutdown();
        }
        return true;
    }

    // 上传文件
    public static String upload(InputStream input, String filename) {
        String  bucketName = OTHER_BUCKETNAME + APPID;
        COSClient cosClient = null;
        String fileName = null;
        try {
            //上传图片
            fileName =filename;
            String substring = fileName.substring(fileName.lastIndexOf("."));
            Random random = new Random();
            //图片名称
            fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
            // 3 生成 cos 客户端。
            cosClient = getCOSClient();
            // 指定要上传到的存储桶，指定要上传到 COS 上对象键
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, input, objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            Date expiration = new Date(System.currentTimeMillis() + 5 * 60 * 10000);
            URL url = cosClient.generatePresignedUrl(bucketName, filename, expiration);
            //图片路径url
            return cosClient.getObjectUrl(bucketName, fileName).toString();
        } finally {
            if (cosClient != null) {
                // 关闭客户端(关闭后台线程)
                cosClient.shutdown();
            }
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static String uploadfile2(String fileName,File localFile) {

        String bucketName = BucketNameType.OTHER_BUCKETNAME + APPID;;
        COSClient cosClient = null;
        try {
            cosClient = getCOSClient();
            //上传图片
            String substring = fileName.substring(fileName.lastIndexOf("."));
            localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()), substring);
            Random random = new Random();
            //图片名称
            fileName = random.nextInt(10000) + System.currentTimeMillis() + substring;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName, fileName, localFile);
            cosClient.putObject(objectRequest);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        //图片路径url
        return cosClient.getObjectUrl(bucketName, fileName).toString();
    }
}
